<template>
  <div class="container mx-auto p-4 max-w-6xl container-whhm">
    <!-- 搜索和新增区域 -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-6 transform transition-all duration-300 hover:shadow-lg">
      <div class="flex flex-col md:flex-row md:items-center justify-between">
        <div class="flex flex-col sm:flex-row gap-3 mb-4 md:mb-0">
          <!-- <div class="relative w-full sm:w-auto">
            <input 
              type="text" 
              v-model="searchQuery" 
              placeholder="搜索持仓信息..." 
              class="pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 w-full sm:w-auto transition-all duration-300"
            >
            <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </div> -->
          
          <button 
            @click="openAddModal" 
            class="bg-blue-500 hover:bg-blue-600 text-white px-5 py-3 rounded-lg transition-all duration-300 flex items-center justify-center gap-2 shadow-md hover:shadow-lg transform hover:-translate-y-0.5"
          >
            <i class="fa fa-plus"></i>
            <span>新增持仓</span>
          </button>
        </div>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="bg-white rounded-xl shadow-md overflow-hidden mb-6 transform transition-all duration-300 hover:shadow-lg">
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">买入时间</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">买入实时均价</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓数量(克)</th>
              <!-- <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓金额</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓利润</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓利润率</th> -->
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓成本价</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">持仓均价</th>
              <th scope="col" class="px-6 py-4 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="item in paginatedItems" :key="item.id" class="hover:bg-gray-50 transition-colors duration-200">              
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ item.buyTime }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">¥{{ item.buyRealPrice }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">{{ item.holdNum }}</td>
              <!-- <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">¥{{ item.holdAmount }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm" :class="{ 'text-green-600 font-medium': item.holdProfit > 0, 'text-red-600 font-medium': item.holdProfit < 0 }">
                ¥{{ item.holdProfit }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm" :class="{ 'text-green-600 font-medium': item.holdProfitRate > 0, 'text-red-600 font-medium': item.holdProfitRate < 0 }">
                {{ item.holdProfitRate }}%
              </td> -->
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">¥{{ item.holdCostPrice }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-medium">¥{{ item.holdCostPriceAvg }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm">
                <div class="flex space-x-2">
                  <button @click="openEditModal(item)" class="text-yellow-500 hover:text-yellow-600 transition-colors duration-200 flex items-center gap-1">
                    <i class="fa fa-pencil"></i>
                    <span class="hidden sm:inline">编辑</span>
                  </button>
                  <button @click="confirmDelete(item.id)" class="text-red-500 hover:text-red-600 transition-colors duration-200 flex items-center gap-1">
                    <i class="fa fa-trash"></i>
                    <span class="hidden sm:inline">删除</span>
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 空数据状态 -->
      <div v-if="filteredItems.length === 0" class="py-12 text-center">
        <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gray-100 mb-4">
          <i class="fa fa-inbox text-gray-400 text-2xl"></i>
        </div>
        <h3 class="text-lg font-medium text-gray-900 mb-2">暂无持仓数据</h3>
        <p class="text-gray-500 mb-4">点击上方"新增持仓"按钮添加第一条记录</p>
        <button @click="openAddModal" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors duration-200">
          <i class="fa fa-plus mr-2"></i>新增持仓
        </button>
      </div>
      
      <!-- 分页控制 -->
      <div class="px-6 py-4 bg-gray-50 flex items-center justify-between">
        <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
          <div>
            <p class="text-sm text-gray-700">
              显示第 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 至 <span class="font-medium">{{ Math.min(currentPage * pageSize, totalItems) }}</span> 条，共 <span class="font-medium">{{ totalItems }}</span> 条记录
            </p>
          </div>
          <div>
            <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
              <button 
                @click="prevPage" 
                :disabled="currentPage === 1" 
                class="relative inline-flex items-center px-4 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
              >
                <span class="sr-only">上一页</span>
                <i class="fa fa-chevron-left"></i>
              </button>
              
              <button 
                v-for="page in pageNumbers" 
                :key="page" 
                :class="{ 'bg-blue-50 border-blue-500 text-blue-600 font-medium': page === currentPage, 'bg-white border-gray-300 text-gray-500 hover:bg-gray-50': page !== currentPage }"
                @click="currentPage = page"
                class="relative inline-flex items-center px-4 py-2 border text-sm transition-all duration-200"
              >
                {{ page }}
              </button>
              
              <button 
                @click="nextPage" 
                :disabled="currentPage === totalPages" 
                class="relative inline-flex items-center px-4 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
              >
                <span class="sr-only">下一页</span>
                <i class="fa fa-chevron-right"></i>
              </button>
            </nav>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑模态框 -->
    <div v-if="isModalOpen" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full animate-fade-in">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg leading-6 font-semibold text-gray-900">
                    {{ isEditing ? '编辑仓库持有状态' : '新增仓库持有状态' }}
                  </h3>
                  <button @click="closeModal" class="text-gray-400 hover:text-gray-500 focus:outline-none">
                    <i class="fa fa-times text-xl"></i>
                  </button>
                </div>
                
                <div class="mt-4 space-y-4">
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="modalBuyTime">
                      买入时间
                    </label>
                    <input 
                      type="datetime-local" 
                      id="modalBuyTime" 
                      class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                      v-model="form.buyTime"
                    >
                  </div>

                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="modalHoldNum">
                      买入实时价格
                    </label>
                    <input 
                      type="number" 
                      step="0.0001" 
                      id="modalHoldNum" 
                      class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                      v-model.number="form.buyRealPrice"
                    >
                  </div>
                  
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="modalHoldNum">
                      持仓数量(克)
                    </label>
                    <input 
                      type="number" 
                      step="0.0001" 
                      id="modalHoldNum" 
                      class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                      v-model.number="form.holdNum"
                    >
                  </div>
                  
                  <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1" for="modalHoldCostPrice">
                      持仓成本价
                    </label>
                    <input 
                      type="number" 
                      step="0.0001" 
                      id="modalHoldCostPrice" 
                      class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors"
                      v-model.number="form.holdCostPrice"
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button 
              type="button" 
              class="w-full inline-flex justify-center px-5 py-3 border border-transparent shadow-sm text-base font-medium rounded-md text-white bg-blue-500 hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200 sm:ml-3 sm:w-auto sm:text-sm"
              @click="saveItem"
            >
              <i class="fa fa-save mr-2"></i>
              保存
            </button>
            
            <button 
              type="button" 
              class="mt-3 w-full inline-flex justify-center px-5 py-3 border border-gray-300 shadow-sm text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              @click="closeModal"
            >
              <i class="fa fa-times mr-2"></i>
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 删除确认模态框 -->
    <div v-if="isDeleteModalOpen" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 transition-opacity" aria-hidden="true">
          <div class="absolute inset-0 bg-gray-500 opacity-75"></div>
        </div>
        
        <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
        
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-md sm:w-full animate-fade-in">
          <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
            <div class="sm:flex sm:items-start">
              <div class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
                <i class="fa fa-exclamation-triangle text-red-500 text-xl"></i>
              </div>
              <div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
                <h3 class="text-lg leading-6 font-medium text-gray-900 mb-2" id="modal-title">
                  确认删除
                </h3>
                <div class="mt-2">
                  <p class="text-sm text-gray-600">
                    你确定要删除这条持仓记录吗？此操作不可撤销，删除后数据将无法恢复。
                  </p>
                </div>
              </div>
            </div>
          </div>
          <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
            <button 
              type="button" 
              class="w-full inline-flex justify-center px-5 py-3 border border-transparent shadow-sm text-base font-medium rounded-md text-white bg-red-500 hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 transition-all duration-200 sm:ml-3 sm:w-auto sm:text-sm"
              @click="deleteItem"
            >
              <i class="fa fa-trash mr-2"></i>
              删除
            </button>
            <button 
              type="button" 
              class="mt-3 w-full inline-flex justify-center px-5 py-3 border border-gray-300 shadow-sm text-base font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-all duration-200 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              @click="closeDeleteModal"
            >
              <i class="fa fa-times mr-2"></i>
              取消
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载中遮罩 -->
    <div v-if="isLoading" class="fixed inset-0 z-40 flex items-center justify-center bg-black bg-opacity-25">
      <div class="bg-white p-6 rounded-lg shadow-lg flex items-center">
        <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-500 mr-4"></div>
        <span class="text-gray-700 font-medium">加载中...</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import axios from "axios";
import dayjs from 'dayjs';

const isLoading = ref(false);

// 分页控制
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref('');
const tableData = ref([]);
const isModalOpen = ref(false);
const isEditing = ref(false);
const isDeleteModalOpen = ref(false);
const deleteId = ref(null);

// 表单数据
const form = ref({
  buyTime: '',
  buyRealPrice: null,
  holdNum: null,
  holdCostPrice: null
});

// 计算属性
const totalItems = computed(() => tableData.value.total || 0);
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value));
const filteredItems = computed(() => tableData.value.records || []);

// 当前页的数据
const paginatedItems = computed(() => {
  return filteredItems.value;
});

// 页码数组
const pageNumbers = computed(() => {
  const numbers = [];
  const maxVisiblePages = 5;
  
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;
  
  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }
  
  for (let i = startPage; i <= endPage; i++) {
    numbers.push(i);
  }
  
  return numbers;
});

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  
  // 如果已经是格式化的字符串，直接返回
  if (typeof dateTime === 'string' && dateTime.includes('-') && dateTime.includes(':')) {
    return dateTime.replace('T', ' ') + ':00';
  }
  
  // 处理时间戳的情况（如果有）
  const date = new Date(dateTime);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 格式化日期为ISO格式（用于datetime-local输入）
const formatDateForInput = (dateTime) => {
  if (!dateTime) return '';
  
  // 处理数据库格式 (YYYY-MM-DD HH:MM:SS)
  if (dateTime.includes(' ')) {
    return dateTime.split(' ')[0] + 'T' + dateTime.split(' ')[1].slice(0, 5);
  }
  
  return dateTime;
};

// 获取数据列表
const fetchData = async () => {
  isLoading.value = true;
  
  try {
    const response = await axios.post("http://localhost:8090/warehouse-hold-situation/page", {
        pageNum: currentPage.value,
        pageSize: pageSize.value
    });
    tableData.value = response.data || { records: [], total: 0 };
  } catch (error) {
    console.error("获取数据失败：", error);
    alert('获取数据失败，请稍后重试');
  } finally {
    isLoading.value = false;
  }
};

// 打开新增模态框
const openAddModal = () => {
  isEditing.value = false;
  form.value = {
    buyTime: formatDateForInput(new Date().toISOString()),
    buyRealPrice: null,
    holdNum: null,
    holdCostPrice: null
  };
  isModalOpen.value = true;
};

// 打开编辑模态框
const openEditModal = (item) => {
  isEditing.value = true;
  form.value = {
    id: item.id,
    buyTime: formatDateForInput(item.buyTime),
    buyRealPrice: item.buyRealPrice,
    holdNum: item.holdNum,
    holdCostPrice: item.holdCostPrice
  };
  isModalOpen.value = true;
};

// 关闭模态框
const closeModal = () => {
  isModalOpen.value = false;
};

// 确认删除
const confirmDelete = (id) => {
  deleteId.value = id;
  isDeleteModalOpen.value = true;
};

// 关闭删除确认模态框
const closeDeleteModal = () => {
  deleteId.value = null;
  isDeleteModalOpen.value = false;
};

// 保存项目
const saveItem = async () => {
  // 简单验证
  if (!form.value.buyTime || 
      form.value.buyRealPrice === null || 
      form.value.holdNum === null || 
      form.value.holdCostPrice === null) {
    alert('请填写所有必填字段');
    return;
  }
  
  isLoading.value = true;
  
  try {
    // 准备保存的数据
    const dataToSave = {
      ...form.value,
      buyTime: formatDateTime(form.value.buyTime)
    };
    
    let response;
    
    if (isEditing.value) {
      // 更新现有记录
      response = await axios.post("http://localhost:8090/warehouse-hold-situation/update", dataToSave);
      alert('更新成功！');
    } else {
      // 添加新记录
      response = await axios.post("http://localhost:8090/warehouse-hold-situation/add", dataToSave);
      alert('添加成功！');
    }
    
    closeModal();
    await fetchData();
  } catch (error) {
    console.error("保存失败：", error);
    alert('保存失败，请稍后重试');
  } finally {
    isLoading.value = false;
  }
};

// 删除项目
const deleteItem = async () => {
  if (deleteId.value !== null) {
    isLoading.value = true;
    
    try {
      await axios.post(`http://localhost:8090/warehouse-hold-situation/deletes`,[deleteId.value]);
      alert('删除成功！');
      closeDeleteModal();
      await fetchData();
    } catch (error) {
      console.error("删除失败：", error);
      alert('删除失败，请稍后重试');
    } finally {
      isLoading.value = false;
    }
  }
};

// 分页控制方法
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
};

// 监听搜索和分页变化，重新加载数据
watch([currentPage, pageSize, searchQuery], () => {
  fetchData();
});

// 页面加载时初始化数据
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.animate-fade-in {
  animation: fadeIn 0.3s ease-in-out;
}
.container-whhm {
  border: 1px solid;
  padding: 15px;
  border-radius: 14px;
  background: #242424;
  height: 489px;
  margin-right: 0px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}
</style>